var http = require('http');

// http://www.zhangongjx.com/auth/login?username=admin&password=631427
var http_request = {
    host:'www.zhangongjx.com',
    port:80,
    // path:'/auth/login' ,
    // method: 'POST',
    headers:{
        "Content-Type": 'application/json'//, "Content-Length": 31
    }
}; 
 

let Request = {
    base: (path, params, method) => {
        console.log(method + ' path:', path, ', params:', params);
        return new Promise((resolve, reject) => {
            http_request.path = path;
            http_request.method = method;
            var req = http.request(http_request,function(response){
                //response.setEncoding('utf-8');
                // console.log("response statusCode: " + response.statusCode);
            
                var buffers = [];
                response.on('data', function(chunk) {
                    buffers.push(chunk);
                });
            
                response.on('end', function(chunk) {
                    var wholeData = Buffer.concat(buffers);
                    var dataStr = wholeData.toString('utf8');
                    console.log('response:', dataStr);
                    if (typeof(dataStr) != 'string') resolve(dataStr)
                    else resolve(JSON.parse(dataStr))
                    //data=wholeData;
                    //res.send(JSON.stringify(buffers));
                });
            
            }).on('error', function(e) {    
                console.log("POST error: " + e.message);
                reject(e)
            });
            method == 'POST' && req.write(JSON.stringify(params))
            req.end(); 
        })
    }
}

module.exports = {
    Post: (path, params) => { 
        return Request.base(path, params, 'POST') 
    },
    Get: (path) => { 
        return Request.base(path, '', 'GET') 
    }
}